package com.cn.sys.main.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import org.springframework.jdbc.core.metadata.TableMetaDataContext;

import com.cn.sys.frame.util.SpringContextUtil;

public class TableColumnUtil {

	private static ConcurrentHashMap<String, List<String>> TABLE_COLUMNS_MAP = new ConcurrentHashMap<String, List<String>>();
	
	public static List<String> get(String tableName) {
		List<String> result = TABLE_COLUMNS_MAP.get(tableName);
		if(result==null||result.isEmpty()){
			//System.out.println("加载表"+tableName+"的字段!");
			DataSource dataSource = SpringContextUtil.getBean("dataSource");
			TableMetaDataContext tableMetaDataContext = new TableMetaDataContext();
			tableMetaDataContext.setTableName(tableName);
			tableMetaDataContext.processMetaData(dataSource, new ArrayList<String>(), new String[]{});
			result = tableMetaDataContext.getTableColumns();
			if(!TABLE_COLUMNS_MAP.containsKey(tableName)){
				TABLE_COLUMNS_MAP.put(tableName, result);
			}
		}
		return result;
	}
	
	public static void reload(String tableName){
		System.out.println("重新加载表"+tableName+"的字段!");
		DataSource dataSource = SpringContextUtil.getBean("dataSource");
		TableMetaDataContext tableMetaDataContext = new TableMetaDataContext();
		tableMetaDataContext.setTableName(tableName);
		tableMetaDataContext.processMetaData(dataSource, new ArrayList<String>(), new String[]{});
		if(TABLE_COLUMNS_MAP.containsKey(tableName)){
			TABLE_COLUMNS_MAP.remove(tableName);
		}
		TABLE_COLUMNS_MAP.put(tableName, tableMetaDataContext.getTableColumns());
	}
}
